package com.lucky.carcodepro.exception;

import com.lucky.carcodepro.domain.enums.ResponseStatusEnums;
import com.lucky.carcodepro.domain.response.Response;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务逻辑异常
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Response<?> handler(BusinessException e, HttpServletRequest request)
    {
        if (e.getIfDz())
        {
            log.error("[业务逻辑异常]", e);
        } else
        {
            log.error("[{}]", e.getLocalizedMessage());
        }
        return Response.success(e.getCode(), e.getMsg());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Response handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return Response.success(ResponseStatusEnums.FAIL);
    }

    /**
     * 系统异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return Response.success(ResponseStatusEnums.FAIL);
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response<?> handler(MethodArgumentNotValidException e, HttpServletRequest request)
    {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String error = ResponseStatusEnums.FAIL.getMsg();
        if (!allErrors.isEmpty())
        {
            error = allErrors.get(0).getDefaultMessage();
        }
        return Response.success(ResponseStatusEnums.FAIL.getCode(), error);
    }
}
